<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";
import Refresh from "@iconify-icons/ep/refresh";
import { Plus } from "@element-plus/icons-vue";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import AppUtil from "@/utils/AppUtil";

import AddFill from "@iconify-icons/ri/add-circle-line";
import { useRoute } from "vue-router";
import Edit from "@iconify-icons/ep/edit";
//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
import { provinceAndCityData, codeToText } from "element-china-area-data";

const route = useRoute();
defineOptions({
  name: "stores"
});
const config = reactive({
  listUrl: "/api/v1/stores",
  addUrl: "/api/v1/stores",
  editUrl: "/api/v1/stores",
  deleteUrl: "/api/v1/stores/delete",
  detailUrl: "",
  title: "门店",

  /**搜索条件 */
  searchForm: [],
  /**
   * 添加/编辑表单
   */
  editForm: [
    //名称     goodsName
    {
      label: "名称",
      prop: "storesName",
      type: "input",
      input: {
        type: "text"
      },

      rules: [{ required: true, message: "请输入名称", trigger: "blur" }]
    },
    //customerAccount 客服账号
    {
      label: "客服账号",
      prop: "customerAccount",
      type: "input",
      input: {
        type: "text",
        placeholder: "请输入客服账号"
      },
      rules: [{ required: true, message: "请输入客服账号", trigger: "blur" }]
    },
    //门店客服 customerUrl
    {
      label: "门店客服",
      prop: "customerUrl",
      type: "input",
      input: {
        type: "text",
        placeholder: "请输入门店客服网址"
      },
      rules: [{ required: true, message: "请输入门店客服", trigger: "blur" }]
    },
    //开始时间 startTime
    {
      label: "开始时间",
      prop: "startTime",
      type: "time",
      time: {
        placeholder: "请选择营业开始时间",
        valueFormat: "HH:mm:ss"
      },
      rules: [{ required: true, message: "请选择开始时间", trigger: "blur" }],
      span: 12
    },
    {
      label: "结束时间",
      prop: "endTime",
      type: "time",
      time: {
        placeholder: "请选择营业结束时间",
        valueFormat: "HH:mm:ss"
      },
      rules: [{ required: true, message: "请选择结束时间", trigger: "blur" }],
      span: 12
    },
    //	logo图片 logoPath
    {
      label: "logo",
      prop: "logoPath",
      type: "uploadOne",
      upload: {
        fileArr: []
      }
    },
    {
      label: "位置",
      prop: "location",
      type: "slot"
    },
    //详细地址 address
    {
      label: "详细地址",
      prop: "address",
      type: "input",
      input: {
        type: "text",
        placeholder: "请输入详细地址,不需要包含省市县"
      },
      rules: [{ required: true, message: "请输入详细地址", trigger: "blur" }]
    },
    {
      label: "负责人",
      prop: "userSid",
      type: "select",

      select: {
        placeholder: "请选择负责人用户",
        options: [],
        filterable: true,
        remote: true,
        loading: false,
        remoteMethod(query, val) {
          // console.log("remoteMethod", query, val);

          if (!val.options || !val.options.length) {
            val.select.loading = true;
            AppUtil.request(
              {
                url: "/api/v1/users/store-manager",
                method: "get"
              },
              (res: any) => {
                res.data.records.map(val => {
                  val.value = val.sid;
                  val.name = val.nickName + "-" + val.userName;
                });
                val.options = val.select.options = res.data.records;
                // console.log("remoteMethod", res.data)
              },
              b => {
                val.select.loading = false;
              }
            );
          } else if (query) {
            val.select.options = val.options.filter(val => {
              return val.name.includes(query);
            });
          } else {
            val.select.options = val.options;
          }
        }
      }
    },
    //status 状态
    {
      label: "状态",
      prop: "status",
      type: "select",
      value: "0",
      select: {
        options: [
          { id: "0", name: "启用" },
          { id: "1", name: "禁用" }
        ]
      }
    }
  ],
  rules: {},
  formData: {},
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      label: "名称",
      prop: "storesName",
      align: "left",
      width: 150,
      slot: "storesName"
    },
    //排序
    {
      label: "负责人",
      prop: "user",
      align: "left",
      slot: "user",
      minWidth: 200
    },
    {
      label: "门店地址",
      prop: "address",
      align: "left",
      minWidth: 250,
      cellRenderer: ({ row }) =>
        row.province + row.city + row.district + row.address
    },

    {
      label: "状态",
      prop: "status",
      align: "left",
      width: 80,
      cellRenderer: ({ row }) => {
        return row.status == 0 ? "启用" : "禁用";
      }
    },

    {
      label: "操作",
      prop: "action",
      width: 150,
      slot: "operation"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  },

  imgArr: [],
  searchData: {},
  showEdit: false,

  id: "",
  /**地址 */
  address: "",
  /**显示地址列表 */
  showAddr: false,
  addrArr: [],
  city: ""
});

const instance = getCurrentInstance();
function update_click(item) {
  console.log("update_click", item);
  config.formData = item;

  config.editForm.map(item1 => {
    //处理封面初始化imgArr

    if (item1.type == "uploadOne") {
      if (item[item1.prop]) {
        item1.upload.fileArr = [
          {
            url: AppUtil.getAliImgUrlByH(item[item1.prop]),
            response: {
              code: 200,
              data: {
                url: item[item1.prop]
              }
            }
          }
        ];
      } else {
        item1.upload.fileArr = [];
      }
    } else if (item1.type == "uploads") {
      let arr = [];
      let valArr = [];
      item[item1.prop].map(item2 => {
        arr.push({
          url: AppUtil.getAliImgUrlByH(
            item2.imgUrl || item2.goodsDesc || item2
          ),
          response: {
            code: 200,
            data: {
              url: item2.imgUrl || item2.goodsDesc || item2
            }
          }
        });
        valArr.push(item2.imgUrl || item2.goodsDesc || item2);
      });
      item1.upload.fileArr = arr;
      config.formData[item1.prop] = valArr;
      // if (item1.prop=='goodsDetails') {
      //   item1.value
      // }
    }
  });
  // // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  console.log("update_click editForm", item);

  pData.showEdit = true;
}
function add_click() {
  if (config.formData.sid) {
    //移除选中的编辑数据，保留上次新增数据
    config.formData = JSON.parse(JSON.stringify(config.defaultData));
    config.editForm.map(item1 => {
      //处理封面初始化imgArr
      if (item1.type == "uploadOne" || item1.type == "uploads") {
        item1.upload.fileArr = [];
      }
    });
  }

  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  pData.showEdit = true;
}

function handleSizeChange(val: number) {
  console.log(`${val} items per page`);
  pData.pagination.pageSize = val;
  reset_list();
}

function handleCurrentChange(val: number) {
  console.log(`current page: ${val}`);
  pData.pagination.currentPage = val;
  onSearch();
}
//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      // res.data.records.map(item => {
      //   let imgArr = [];
      //   let bigArr = [];
      //   item.pg_hb &&
      //     item.pg_hb.map(item1 => {
      //       imgArr.push(AppUtil.getAliImgUrlByW(item1, 200));
      //       bigArr.push(AppUtil.imgHost + item1);
      //     });
      //   item.imgArr = imgArr;
      //   item.bigArr = bigArr;
      // });
      pData.dataArr = res.data.records;
      pData.pagination.total = res.data.total * 1;
      pData.pagination.currentPage = res.data.current * 1;
    },
    b => (pData.loading = false)
  );
}
onSearch();

function handleDelete(item) {
  AppUtil.request(
    {
      url: config.deleteUrl,
      method: "PUT",
      data: {
        sidList: [item.sid]
      }
    },
    res => {
      onSearch();
    }
  );
}

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  instance.proxy.$refs["vForm"].validate(valid => {
    if (!valid) return;
    pData.reqing = true;

    let formData = JSON.parse(JSON.stringify(config.formData));
    delete formData.sid;

    AppUtil.request(
      {
        url: config.formData.sid
          ? config.editUrl + "/" + config.formData.sid
          : config.addUrl,
        method: config.formData.sid ? "put" : "post",
        data: formData
      },
      res => {
        // console.log("banner", res);
        instance.proxy.$message.success(
          config.formData.sid ? "修改成功" : "添加成功"
        );
        onSearch();
        pData.showEdit = false;
      },
      b => {
        pData.reqing = false;
      }
    );
  });
}
let map = null;
let search = new TMap.service.Search({ pageSize: 10 }); // 新建一个地点搜索类

let markers;
function edit_open() {
  console.log("edit_open");
  if (map) {
    if (config.formData.latitude) {
      map.setCenter(
        new TMap.LatLng(config.formData.latitude, config.formData.longitude)
      );
    }
  } else {
    setTimeout(() => {
      var center = new TMap.LatLng(39.984104, 116.307503);
      //初始化地图
      map = new TMap.Map("container", {
        rotation: 20, //设置地图旋转角度
        pitch: 30, //设置俯仰角度（0~45）
        zoom: 12, //设置地图缩放级别
        center: center //设置地图中心点坐标
      });
      markers = new TMap.MultiMarker({
        map: map,
        geometries: []
      });
      //监听地图点击事件
      map.on("click", function (evt) {
        var lat = evt.latLng.getLat().toFixed(6);
        var lng = evt.latLng.getLng().toFixed(6);
        console.log("click", evt.latLng);
        markers.setGeometries([]);
        markers.updateGeometries([
          {
            id: "1",
            position: evt.latLng
          }
        ]);
        config.formData.latitude = lat;
        config.formData.longitude = lng;
      });
    }, 300);
  }
}
function choose_addr(addr) {
  console.log("choose_addr", addr);
  pData.showAddr = false;
  markers.setGeometries([]);
  markers.updateGeometries([
    {
      id: addr.id + "",
      position: addr.location
    }
  ]);
  map.setCenter(addr.location);
  config.formData.address = addr.address || addr.title;
  //province
  config.formData.province = addr.province;
  config.formData.city = addr.city;
  config.formData.district = addr.district;
  config.formData.districtCode = addr.adcode;
  config.formData.latitude = addr.location.lat;
  config.formData.longitude = addr.location.lng;
}
function search_addr() {
  // console.log("addr", pData.address);

  // console.log("城市", pData.city);
  // console.log("provinceAndCityData", codeToText[pData.city[1]]);

  // // console.log(codeToText(pData.city));

  // return;
  if (!pData.city || pData.city.length < 1) {
    return instance.proxy.$alert("请选择城市");
  }

  // 新建一个地点搜索类
  var suggest = new TMap.service.Suggestion({
    // 新建一个关键字输入提示类
    pageSize: 10, // 返回结果每页条目数
    region: codeToText[pData.city[1]],
    regionFix: true // 搜索无结果时是否固定在当前城市
  });
  suggest
    .getSuggestions({ keyword: pData.address, location: map.getCenter() })
    .then(result => {
      // 以当前所输入关键字获取输入提示
      console.log("搜索结果", result);
      if (result.data.length < 1) {
        return instance.proxy.$alert(" 无搜索结果 ");
      }
      pData.addrArr = result.data;
      pData.showAddr = true;

      // setTimeout(() => {
      //   map.setCenter(result.data[0].location);
      // }, 300);
      // suggestionListContainer.innerHTML = '';
      // suggestionList = result.data;
      // suggestionList.forEach((item, index) => {
      //   suggestionListContainer.innerHTML += `<li><a href="#" onclick="setSuggestion(${index})">${item.title}<span class="item_info">${item.address}</span></a></li>`;
      // });
    })
    .catch(error => {
      console.log(error);
      instance.proxy.$alert(error.message || "搜索失败");
    });
  // search
  //   .searchRectangle({
  //     keyword: pData.address,
  //     bounds: map.getBounds()
  //   })
  //   .then(result => {
  //     console.log("搜索结果", result);

  //     markers.setGeometries([]);
  // if (result.data.length < 1) {
  //   return instance.proxy.$alert(" 无搜索结果 ");
  // }
  // markers.updateGeometries([
  //   {
  //     id: "1",
  //     position: result.data[0].location
  //   }
  // ]);
  //     // result.data.forEach((item, index) => {
  //     //   var geometries = markers.getGeometries();

  //     //   geometries.push({
  //     //     id: String(index), // 点标注数据数组
  //     //     position: item.location
  //     //   });
  //     //   markers.updateGeometries(geometries); // 绘制地点标注
  //     // });
  //   })
  //   .catch(error => {
  //     // return console.log("搜索失败", error);
  //     instance.proxy.$alert(error.message || "搜索失败");
  //     // instance.proxy.$message.error(error.message);
  //     // ?return console.log("搜索失败", error);
  //   });
}
</script>

<template>
  <div class="main">
    <el-form
      v-if="config.searchForm && config.searchForm.length > 0"
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select>
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      :title="config.title + '管理'"
      :columns="config.columns"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          v-if="config.addUrl"
          type="primary"
          :icon="useRenderIcon(upload)"
          @click="add_click"
        >
          新增{{ config.title }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          :data="pData.dataArr"
          :columns="dynamicColumns"
          :loading="pData.loading"
          :size="size"
          :pagination="pData.pagination"
          :paginationSmall="size === 'small' ? true : false"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <!-- imagePath -->
          <template #storesName="{ row }">
            <el-image
              style="width: 120px; height: 120px"
              fit="cover"
              :src="AppUtil.getAliImgUrlByW(row.logoPath, 200)"
            />
            <div style="text-align: center">{{ row.storesName }}</div>
          </template>
          <template #user="{ row }">
            <div>姓名:{{ row.userName }}</div>
            <div>电话:{{ row.userPhone }}</div>
            <div>客服:{{ row.customerUrl }}</div>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="update_click(row)"
            >
              修改
            </el-button>

            <el-popconfirm
              :title="`是否确认删除这条数据`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.sid ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
      @open="edit_open"
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config">
          <template #location="{ row }">
            <div style="display: flex">
              <div style="width: 200px">
                <el-cascader
                  v-model="pData.city"
                  placeholder="选择省/市"
                  :options="provinceAndCityData"
                />
              </div>
              <el-popover
                :visible="pData.showAddr"
                placement="bottom"
                width="440px"
              >
                <div
                  v-for="(addr, i) in pData.addrArr"
                  :key="i"
                  style="margin-bottom: 0.5rem; min-width: 200px"
                  @click="choose_addr(addr)"
                >
                  {{ addr.address || addr.title }}
                </div>
                <template #reference>
                  <el-input
                    v-model="pData.address"
                    placeholder="搜索地址"
                    style="margin-bottom: 0.5rem"
                  >
                    <template #append>
                      <div style="cursor: pointer" @click="search_addr">
                        搜索
                      </div>
                    </template>
                  </el-input>
                </template>
              </el-popover>
            </div>

            <div id="container" style="width: 100%; height: 300px" />
            <div v-if="config.formData.latitude">
              坐标：{{ config.formData.latitude }},{{
                config.formData.longitude
              }}
            </div>
            <!-- <div>姓名:{{ row }}</div> -->
            <!-- <tmap-map
              mapKey="O3WBZ-WUBLI-3QOGJ-UOY7D-NQ6I7-E2FRM"
              style="width: 200px; height: 200px"
              :center="{ lat: 30.290756, lng: 120.074387 }"
              :zoom="10"
              :control="{ scale: {}, zoom: { position: 'bottomRight' } }"
            /> -->
          </template>
        </Form>
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
